<?php

/**
 * EmsElement form.
 *
 * @package    ems1
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class EmsElementForm extends BaseEmsElementForm
{
    public function configure()
    {
        unset(
            $this['created_at'], $this['updated_at'], $this['published'],
            $this['is_enabled']
        );

        $this->setWidget('section_id', new sfWidgetFormInputHidden());
        $this->setWidget('header_id', new sfWidgetFormInputHidden());
        $this->setWidget('footer_id', new sfWidgetFormInputHidden());        
        $this->setWidget('type_id', new sfWidgetFormInputHidden());

        $this->validatorSchema['title']->setMessage('required', 'Campo obligatorio.');

        if ($this->getObject()->exists())
        {
            $this->widgetSchema['published'] = new sfWidgetFormInputCheckbox(array('label' => 'Publicar'));
            $this->validatorSchema['published'] = new sfValidatorBoolean();
            $this->widgetSchema['is_enabled'] = new sfWidgetFormInputCheckbox(array('label' => 'Habilitar'));
            $this->validatorSchema['is_enabled'] = new sfValidatorBoolean();
        }
        
        if($this->getObject()->getSectionId()){
            if($this->getObject()->exists()) {
                $range = range(1, strlen($this->getObject()->getSection()->getStructure()));
            } else {
                $range = range(1, strlen($this->getObject()->getSection()->getStructure())+1);
            }
            $position_options = array_combine($range, $range);
        } else {
            $counter = $this->getOption('counter'); //use for setting the element position when it'll be rendered
            $range = range(1, $counter);
            $position_options = array_combine($range, $range);
        }

        $this->setWidget('position', new sfWidgetFormChoice(array(
            'choices'  => $position_options,
            'expanded' => false,
            'multiple' => false
        )));

        $this->validatorSchema['position'] = new sfValidatorChoice(array(
            'choices' => array_keys($position_options),
        ));

        $this->widgetSchema->setLabels(array(
            'title' => 'Nombre',
            'position' => 'Posición'
            ));

        switch ($this->getObject()->getType()->getType()) {
            case 'Menu':
                if(!$this->getObject()->exists()){
                    $this->setDefault('title', 'Menú Secundario');
                    $menu = new EmsMenu();
                    $this->getObject()->setMenu($menu);
                }

                $form = new EmsMenuForm($this->getObject()->getMenu(),
                        array('portal_id' => $this->getOption('portal_id')));
                $this->embedForm('Menu', $form);

                break;
            case 'Form':
                if(!$this->getObject()->exists()){
                    $formObj = new EmsForm();
                    $this->getObject()->setForm($formObj);
                }

                $form = new EmsFormForm($this->getObject()->getForm());
                $this->embedForm('Form', $form);

                break;
            case 'FeaturesBlock':
                if(!$this->getObject()->exists()){
                    $features_block = new EmsFeaturesBlock();
                    $this->getObject()->setFeaturesBlock($features_block);
                }

                $form = new EmsFeaturesBlockForm($this->getObject()->getFeaturesBlock(),
                        array(
                            'portal_id' => $this->getOption('portal_id'),
                            'content_type' => $this->getOption('content_type', 0)
                        ));
                $this->embedForm('FeaturesBlock', $form);

                break;
            case 'Banner':
                if(!$this->getObject()->exists()){
                    $banner = new EmsBanner();
                    $this->getObject()->setBanner($banner);
                }
                
                $form = new EmsBannerForm($this->getObject()->getBanner(),
                        array('portal_id' => $this->getOption('portal_id')));
                $this->embedForm('Banner', $form);
                
                break;
            default:
                break;
        }

        if($this->getObject()->getHeaderId() || $this->getObject()->getFooterId()){
            unset ($this['section_id']);
            if($this->getObject()->getHeaderId()){
                unset ($this['footer_id']);
            } else {
                unset ($this['header_id']);
            }
        } else {
            unset ($this['header_id'], $this['footer_id']);
        }
    }

    public function addMenuOption ($num)
    {
        $form = $this->getEmbeddedForm('Menu');
        $form->setOption('portal_id', $this->getOption('portal_id'));
        $form->addOption($num);
        $this->embedForm('Menu', $form);
    }

    public function addFeatureForm ($num)
    {
        $form = $this->getEmbeddedForm('FeaturesBlock');
        $form->setOption('portal_id', $this->getOption('portal_id'));
        $form->addFeature($num);
        $this->embedForm('FeaturesBlock', $form);
    }

    public function addFormFieldForm ($num)
    {
        $form = $this->getEmbeddedForm('Form');
        $form->setOption('portal_id', $this->getOption('portal_id'));
        $form->addField($num);
        $this->embedForm('Form', $form);
    }

    public function createElementStructure(EmsElementType $type, array $taintedValues = null, array $taintedFiles = null)
    {
        $to_remove = array ();
        switch ($type->getType()){
            case 'Menu':
                foreach ($taintedValues['Menu']['Options'] as $i => $option)
                {
                    if (!isset($this['Menu']['Options'][$i]) && 
                            ($option['section_id'] !== '' || $option['title'] !== '' || $option['link'] !== ''))
                    {
                        $this->addMenuOption($i);
                    } elseif ($option['section_id'] == '' && $option['title'] == '' && $option['link'] == '') {
                        array_push($to_remove,$i);
                    }
                }
                break;
            case 'FeaturesBlock':
                foreach ($taintedValues['FeaturesBlock']['Features'] as $i => $feature)
                {
                    if (!isset($this['FeaturesBlock']['Features'][$i]) && $feature['content_id']!='')
                    {
                        $this->addFeatureForm($i);
                    } else {
                        array_push($to_remove,$i);
                    }
                }
                break;
            case 'Form':
                foreach ($taintedValues['Form']['Fields'] as $i => $option)
                {
                    if (!isset($this['Form']['Fields'][$i]) )
                    {
                        $this->addFormFieldForm($i);
                    }
                }
                break;
            default:
                break;
        }
        return $to_remove;
    }

    public function bind(array $taintedValues = null, array $taintedFiles = null)
    {
        $to_remove = array ();
        if (isset($taintedValues[$this->getObject()->getType()->getType()]))
        {
            $to_remove = $this->createElementStructure($this->getObject()->getType(), $taintedValues, $taintedFiles);
        }

        switch ($this->getObject()->getType()->getType()) {
            case 'Menu':
                foreach ($to_remove as $key ) {
                    unset ($taintedValues['Menu']['Options'][$key]);
                }
                break;

            default:
                break;
        }
        
        parent::bind($taintedValues, $taintedFiles);
    }

    /*
     *  En el caso en el que el elemento esté relacionado a una sección,
     *  Se actualiza la estructura de la misma en función de mantener congruencia con la
     *  posición que debe ocupar el elemento a la hora de ser impreso en la sección.
     */
    protected function doUpdateObject($values)
    {
        $element = $this->getObject();

        if(!is_null($element->getSectionId())){
            $section = $element->getSection();
            $structure = $section->getStructure();
            if ($element->exists()) {
                if($values['position'] != $element->getPosition()) {
                    $structure = substr_replace($structure, '', $element->getPosition()-1, 1);
                    $structure = Util::str_insert('e', $structure, $values['position']-1);

                    $section->setStructure($structure);
                    $section->save();

                    $this->updateSectionElementsPositions($values['position']);
                }

            } else {
                if($values['position'] == strlen($structure)){
                    $structure = $structure.'e';
                } else {
                    $structure = Util::str_insert('e', $structure, $values['position']-1);

                    $this->updateSectionElementsPositions($values['position']);
                }

                $section->setStructure($structure);
                $section->save();
            }
        }
        parent::doUpdateObject($values);
    }

    /*
     *  
     */
    protected function updateSectionElementsPositions($position){
        $element = $this->getObject();

        foreach ($element->getSection()->getEnabledAndPublishedElements() as $elem) {
            if($elem !== $element && $elem->getPosition() >= $position){
                $new = $elem->getPosition() + 1;
                $elem->setPosition($new);
                $elem->save();
            }
        }
    }
}
